package com.ljkj.cordial.chat.notify;

import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;

import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.util.SharedUserUtils;

/**
 * @description:
 * @author: Panwei
 * @date: 2020/1/11 13:07
 */
public class PromptTone {

    private static final long RING_INTERVAL = 1000;
    private static long mLastRingTime;

    PromptTone() {
    }

    static void ring(Context context) {
        ringWithVibrator(context, false);
    }


    static void ringWithVibrator(Context context) {
        ringWithVibrator(context, true);
    }

    static void ringWithVibrator(Context context, boolean isVibrator) {
        boolean is_r = (boolean) SharedUserUtils.get(context, Canstants.KEY_SYS_IS_MESSAGE_TONE, true);
        if (!is_r) return;
        try {
            long currentRingTime = System.currentTimeMillis();
            if (mLastRingTime == 0 || abs(currentRingTime - mLastRingTime) > RING_INTERVAL) {
                mLastRingTime = currentRingTime;
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(context, notification);
                r.play();
                if (isVibrator) {
                    vibrate(context, 400);
                }
            }
        } catch (Exception e) {
            Logger.print(e.getLocalizedMessage());
        }
    }

    public static void vibrate(Context context, long milliseconds) {
        try {
            Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(milliseconds);
        } catch (Exception e) {
            Logger.print(e.getLocalizedMessage());
        }
    }

    private static long abs(long time) {
        if (time < 0) {
            time = -time;
        }
        return time;
    }
}
